using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

using Microsoft.Practices.CompositeUI;
using Microsoft.Practices.CompositeUI.Utility;
using Microsoft.Practices.CompositeUI.EventBroker;

using LibrErian.Model;
using LibrErian.Common;
using LibrErian.Interfaces.Services;

namespace LibrErian.Modules.BasicBook
{
    public class BookListViewPresenter : Presenter<IBookListView>
	{
        [EventPublication("event://SelectedBookChanged", PublicationScope.WorkItem)]
        public event EventHandler<EventArgs<Book>> SelectedBookChanged;

        private IBookService bookService;

        [ServiceDependency]
        public IBookService BookService
        {
            set
            {
                bookService = value;
            }
        }

        public IList GetBooks()
        {
            return bookService.GetBooks();
        }

        public IList GetBooksByGenre(int genreId)
        {
            return bookService.GetBooksByGenre(genreId);
        }

        public IList GetBooksByAuthor(int authorId)
        {
            return bookService.GetBooksByAuthor(authorId);
        }

        [EventSubscription("event://BooksDataUpdated", ThreadOption.UserInterface)]
        public void BooksDataUpdated(object sender, EventArgs args)
        {
            View.ShowBooks(GetBooks());
        }

        [EventSubscription("event://DisplayFilterChanged", ThreadOption.UserInterface)]
        public void ApplyFilter(object sender, EventArgs<SearchArgs> args)
        {
            IList data = null;
            if (args.Data.SearchType == SearchType.Genre)
            {
                data = GetBooksByGenre(args.Data.Key);
            }
            else if (args.Data.SearchType == SearchType.Author)
            {
                data = GetBooksByAuthor(args.Data.Key);
            }
            else if (args.Data.SearchType == SearchType.All)
            {
                data = GetBooks();
            }
            
            View.ShowBooks(data);
        }

        public void OnSelectionChanged(Book book)
        {
            if (SelectedBookChanged != null)
            {
                SelectedBookChanged(this, new EventArgs<Book>(book));
            }
        }
    }

    public interface IBookListView
    {
        void ShowBooks();
        void ShowBooks(IList data);
    }
}
